import {ElMessage, ElMessageBox, ElNotification} from "element-plus";
import useDictStore from "@/store/modules/dict";
import useEnumsStore from "@/store/modules/enums";
import useUserStore from "@/store/modules/user";
import initListStore from "@/store/modules/initList";
import {StrUtil} from "@/utils/StrUtil";

export const svc = 'icims-api'

export function getEnv() {
    const domain = window.location.hostname
    switch (domain) {
        case "localhost":
        case "127.0.0.1":
            return "local"
        case "icims.47.238.196.250.nip.io":
            return "dev"
        case "icims-admin.z-cloud.ltd":
            return "test"
        default:
            return null
    }
}

export function isDebugMode() {
    let env = getEnv()
    return env === 'debug'//'local'
}

export function getListPageSize() {
    return 1000
}

export function matchPageSize(pageSize) {
    if (!pageSize) {
        return false
    }
    return getPageSizeArr().includes(pageSize)
}

export function getPageSizeArr() {
    return [10, 20, 30, 50]
}

export function checkAuthCode(code) {
    if (!code) {
        return true
    }
    let result = false
    useUserStore().permissions.map(item => {
        if (code === item.permissionCode && result === false) {
            result = true
        }
    })
    return result
}

export function showEnumKeyLabel(enumType, key) {
    if (isNullOrUndefinedOrEmpty(key)) {
        return ''
    }
    let label = key
    if (enumType) {
        let enums = useEnumsStore().getEnums(enumType)
        if (isNullOrUndefined(enums)) {
            return label
        }
        enums.map(item => {
            if (item.key === key) {
                label = key + '[' + item.value + ']'
            }
        })
    }
    return label
}

export function showEnumLabel(enumType, key) {
    if (isNullOrUndefinedOrEmpty(key)) {
        return ''
    }
    let label = key
    if (enumType) {
        let enums = useEnumsStore().getEnums(enumType)
        if (isNullOrUndefined(enums)) {
            return label
        }
        enums.map(item => {
            if (item.key === key) {
                label = item.value
            }
        })
    }
    return label
}

export function getEnumList(enumType) {
    return useEnumsStore().getEnums(enumType)
}

export function showDictKeyLabel(dictType, key) {
    if (isNullOrUndefinedOrEmpty(key)) {
        return '';
    }
    let label = key
    if (dictType) {
        let dicts = useDictStore().getDicts(dictType)
        if (isNullOrUndefined(dicts)) {
            return label
        }
        dicts.map(item => {
            if (item.key === key) {
                label = key + '-' + item.value
            }
        })
    }
    return label
}

export function showDictLabel(dictType, key) {
    if (isNullOrUndefinedOrEmpty(key)) {
        return '';
    }
    let label = key
    if (dictType) {
        let dicts = useDictStore().getDicts(dictType)
        if (isNullOrUndefined(dicts)) {
            return label
        }
        dicts.map(item => {
            if (item.key === key) {
                label = item.value
            }
        })
    }
    return label
}

export function getDictList(dictType) {
    return useDictStore().getDicts(dictType)
}

export function showIdLabel(items, id, field) {
    if (isNullOrUndefinedOrEmpty(id))
        return ''
    let label = id;
    let ids = id.split(',')
    if (ids.length === 0) {
        return ""
    }
    if (typeof(items) === 'object' && items.length > 0 && field && label) {
        let matches = items.filter(item => ids.includes(item.id))
        if (matches.length > 0) {
            let labels = matches.map(m => m[field])
            label = labels.join(',')
        }
    }
    return label;
}

export function customValidator(rule, value, callback) {
    if (rule.required || rule.min > 0) {
        if (isNullOrUndefinedOrEmpty(value)) {
            callback(new Error(rule.label + '为必填项'))
            return
        }
    }
    if (rule.min > 0 && value && value.length < rule.min) {
        callback(new Error(rule.label + '长度不能少于' + rule.min + '个字符'))
        return
    }
    if (rule.max > 0 && value && value.length > rule.max) {
        callback(new Error(rule.label + '长度不能超过' + rule.max + '个字符'))
        return
    }
    if (rule['minValue'] !== undefined && rule['minValue'] > 0 && value < rule['minValue']) {
        callback(new Error(rule.label + '的值不能小于' + rule['minValue'] + ''))
        return
    }
    if (rule['maxValue'] !== undefined && rule['maxValue'] > 0 && value > rule['maxValue']) {
        callback(new Error(rule.label + '的值不能大于' + rule['maxValue'] + ''))
        return
    }
    if (rule.noChinese && StrUtil.includeChinese(value)) {
        callback(new Error(rule.label + '不能包含中文'))
        return
    }
    if (rule.englishNumberUnderline && !StrUtil.englishNumberUnderline(value)) {
        callback(new Error(rule.label + '必须以英文字母开头，只能包含英文字母、数字、下划线'))
    }
    callback()
}

export function alertInfoMsg(msg) {
    alertMsg('info', 2000, msg)
}

export function alertSuccessMsg(msg) {
    alertMsg('success', 2000, msg)
}

export function alertWarningMsg(msg) {
    alertMsg('warning', 10000, msg)
}

export function alertErrorMsg(msg) {
    alertMsg('error', 0, msg)
}

// 顶部向下弹层
function alertMsg(type, duration, msg) {
    let o = {
        message: msg,
        type: type,
        duration: duration,
        showClose: true,
        center: true,
        dangerouslyUseHTMLString: true
    }
    switch (type) {
        case "info":
            ElMessage.info(o)
            return
        case "success":
            ElMessage.success(o)
            return
        case "warning":
            ElMessage.warning(o)
            return
        case "error":
            ElMessage.error(o)
            return
    }
}

export function alertInfo(msg) {
    alert('info', msg)
}

export function alertSuccess(msg) {
    alert('success', msg)
}

export function alertWarning(msg) {
    alert('warning', msg)
}

export function alertError(msg) {
    alert('error', msg)
}

// 中间弹层，有蒙层
function alert(type, msg) {
    ElMessageBox.alert(msg, "系统提示", { type: type })
}

export function notifyInfo(msg) {
    notify('info', 3000, msg)
}

export function notifySuccess(msg) {
    let content = msg || '操作成功'
    notify('success', 3000, content)
}

export function notifyWarning(msg) {
    notify('warning', 10000, msg)
}

export function notifyError(msg) {
    notify('error', 0, msg)
}

// 右侧通知
function notify(type, duration, msg) {
    let o = {
        message: msg,
        type: type,
        duration: duration,
        dangerouslyUseHTMLString: true
    }
    switch (type) {
        case "info":
            o.title = '提示'
            ElNotification.info(o)
            return
        case "success":
            o.title = '成功'
            ElNotification.success(o)
            return
        case "warning":
            o.title = '警告'
            ElNotification.warning(o)
            return
        case "error":
            o.title = '错误'
            ElNotification.error(o)
            return
    }
}

export function arrChangeTreeFn(list, pid= null, parentLevel = 0) {
    if (!list) {
        return null
    }
    let r
    let isParent = list.every(item => item.parentId)
    if(!isParent) {
        r = list.filter((item) =>
            !pid ? isNullOrUndefined(item.parentId) : item.parentId === pid
        )
        .map(item => {
            item.level = parentLevel + 1
            item.children = arrChangeTreeFn(list, item.id, parentLevel + 1)
             return item
        })
    } else {
        r = list
    }
    return r
}

export function objKeyBuild(obj) {
    if (obj) {
      if (typeof(obj) === 'object') {
        if (obj.length) {
          return obj[obj.length - 1]
        }
        return obj
      }
      return obj
    }
    return ''
}

export function convertMemory(v) {
    if (!v) {
        return v
    }
    if (v >= 1024 * 1024 * 1024 * 1024) {
        return ((v * 1.0) / (1024 * 1024 * 1024 * 1024)).toFixed(2) + "TB"
    }
    if (v >= 1024 * 1024 * 1024) {
        return ((v * 1.0) / (1024 * 1024 * 1024)).toFixed(2) + "GB"
    }
    if (v >= 1024 * 1024) {
        return ((v * 1.0) / (1024 * 1024)).toFixed(2) + "MB"
    }
    if (v >= 1024) {
        return ((v * 1.0) / 1024).toFixed(2) + "KB"
    }
    return v
}

export function convertDuration(ms) {
    if (!ms) {
        return ms
    }
    if (ms > 1000 * 60 * 60 * 24) {
        return "大于" + (ms / (1000 * 60 * 60 * 24)) + "天"
    }
    if (ms > 1000 * 60 * 60) {
        return ((ms * 1.0) / (1000 * 60 * 60)).toFixed(2) + "小时"
    }
    if (ms > 1000 * 60) {
        return ((ms * 1.0) / (1000 * 60)).toFixed(2) + "分钟"
    }
    if (ms > 1000) {
        return ((ms * 1.0) / (1000)).toFixed(3) + "秒"
    }
    return ms + "毫秒"
}

Date.prototype.pattern = function (fmt) {
    let o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours() % 12 === 0 ? 12 : this.getHours() % 12, //小时
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    let week = {
        "0": "/u65e5",
        "1": "/u4e00",
        "2": "/u4e8c",
        "3": "/u4e09",
        "4": "/u56db",
        "5": "/u4e94",
        "6": "/u516d"
    };
    if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substring(4 - RegExp.$1.length));
    }
    if (/(E+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, ((RegExp.$1.length > 1) ? (RegExp.$1.length > 2 ? "/u661f/u671f" : "/u5468") : "") + week[this.getDay() + ""]);
    }
    for (let k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        }
    }
    return fmt;
}

export function bytesToSize(size) {
    if (!size) {
        return ""
    }
    size = parseFloat(size)
    if (size < 0.1 * 1024) {
        size = size.toFixed(2) + "B";//小于0.1KB，则转化成B
    } else if (size < 0.1 * 1024 * 1024) {
        size = (size / 1024).toFixed(2) + "KB";// 小于0.1MB，则转化成KB
    } else if (size < 0.1 * 1024 * 1024 * 1024) {
        size = (size / (1024 * 1024)).toFixed(2) + "MB";// 小于0.1GB，则转化成MB
    } else if (size < 0.1 * 1024 * 1024 * 1024 * 1024) {
        size = (size / (1024 * 1024 * 1024)).toFixed(2) + "GB";//小于0.1TB，则转化成GB
    } else {
        size = (size / (1024 * 1024 * 1024 * 1024)).toFixed(2) + "TB";// 其他转化成TB
    }
    // 转成字符串
    let sizeStr = size + ""
    // 获取小数点处的索引
    let index = sizeStr.indexOf(".")
    // 获取小数点后两位的值
    let dou = sizeStr.substr(index + 1, 2);
    // 判断后两位是否为00，如果是则删除00
    if (dou === "00")
        return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2);
    return size;
}

// 数字转中文大写
export function DX(n) {
    if (!/^(0|[1-9]\d*)(\.\d+)?$/.test(n))
        return "数据非法";
    let unit = "千百拾亿千百拾万千百拾元角分", str = "";
        n += "00";
    let p = n.indexOf('.');
    if (p >= 0)
        n = n.substring(0, p) + n.substr(p+1, 2);
        unit = unit.substr(unit.length - n.length);
    for (let i= 0; i < n.length; i++)
        str += '零壹贰叁肆伍陆柒捌玖'.charAt(n.charAt(i)) + unit.charAt(i);
    return str.replace(/零([千百拾角])/g, "零").replace(/(零)+/g, "零").replace(/零([万亿元])/g, "$1").replace(/(亿)万|壹(拾)/g, "$1$2").replace(/^元零?|零分/g, "").replace(/元$/g, "元整");
}

export function getImageUrl(name) {
    return new URL(`../../lib/Carousel/assets/${name}`, import.meta.url).href
}

export function isNullOrUndefined(o) {
    return o === null || o === undefined
}

export function isNullOrUndefinedOrEmpty(o) {
    return o === null || o === undefined || o === ''
}

export function getDaysBetween(date1, date2) {
    if (isNullOrUndefined(date1) || isNullOrUndefined(date2)) {
        return null
    }
    let startDate = Date.parse(date1);
    let endDate = Date.parse(date2);
    if (startDate > endDate) {
        return 0;
    }
    if (startDate === endDate) {
        return 1;
    }
    return (endDate - startDate) / (24 * 60 * 60 * 1000)
}

export function genQrcodeStr(businessType, businessId, businessNo) {
    return businessType + "__" + businessId + "__" + businessNo
}

// com.peas.platform.module.icims.base.approve.enums.ApproveOrderOperType
export function approveOrderOperTypes() {
    return {
        submit: "1",// "提交", CommonElType.info),
        approve: "2",// "审批", CommonElType.primary),
        revocation: "3",// "撤回", CommonElType.danger),
        print: "3-1",// "打印", CommonElType.info),
        replenish: "3-2",// "录入收支信息", CommonElType.info),
        receipt: "5",// "确认收单", CommonElType.info),
        paying: "6",// "支付处理", CommonElType.info),
        complete: "7",// "完结", CommonElType.info),
    }
}

// com.peas.platform.module.icims.base.approve.enums.ApproveOrderBusinessType
export function approveOrderBusinessTypes() {
    return {
        budgetProjectTwo: '1001', // "二级项目申报"
        budgetOne: '1002', // "预算编制（一上）"
        budgetTwo: '1003', // "预算编制（二上）"
        budgetNew: '1004', // "年中新预算"
        budgetAdjust: '1005', // "年中预算调整"
        expenditureKpi: '2001', // "指标单"
        expenditureQuota: '2002', // "额度下达单"
        expenditureAdjustment: '2003', // "调整单"
        expenditureApplication: '2004', // "用款申请单"
        expenditureReimbursement: '2005', // "报账单"
        expenditureReimbursementOther: '2006', // "其他报账单"
        contractInitial: '3001', // "初始合同"
        contractMain: '3002', // "主合同"
        contractSupplemental: '3003', // "合同补充协议"
        contractChange: '3004', // "合同变更"
        contractCash: '3005', // "合同请款"
        contractBorrow: '3006', // "合同借阅"
        contractChecking: '3007', // "合同验收"
        contractInterrupt: '3008', // "合同中止"
        contractTerminate: '3009', // "合同终止"
    }
}

export function commonEnableDisables() {
    return {
        enabled: '1',
        disabled: '0',
    }
}

// 数据更新
export async function initListUpdate (list, path) {
   await initListStore().listUpdate(list, path)
}
